package vn.ducquoc.cassandra;

import java.util.ArrayList;
import java.util.List;

import org.apache.cassandra.thrift.Cassandra;
import org.apache.cassandra.thrift.CfDef;
import org.apache.cassandra.thrift.KsDef;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;

/**
 * Cassandra Create example.
 * 
 * @author ducquoc
 */
public class CassandraThriftCreate {

  public static final String CASSANDRA_HOST = "192.168.22.84";// "tlcirrusa03";
  public static final int CASSANDRA_PORT = 9160;

  public static final String SAMPLE_KEYSPACE = "prstest";
  public static final String SAMPLE_COLUMN_FAMILY = "ductest";

  static final long TIMESTAMP = 1010102011000L;// System.currentTimeMillis();

  public static void main(String[] args) throws Exception {
    TTransport transport = new TFramedTransport(new TSocket(CASSANDRA_HOST,
            CASSANDRA_PORT));
    TProtocol protocol = new TBinaryProtocol(transport);
    Cassandra.Client client = new Cassandra.Client(protocol);
    transport.open();

    System.out.println("Creation Thrift " + client.describe_version());

    // release resources
    transport.flush();
    transport.close();
  }


  public Cassandra.Iface getConnection(String keyspace) throws Exception {
    Cassandra.Iface connection = new ThreadLocal<Cassandra.Iface>().get();
    if (keyspace != null) {
      connection.set_keyspace(keyspace);
    }
    return connection;
  }

  public void addKeyspace(String keyspace) throws Exception {
    List<CfDef> cfDefList = new ArrayList<CfDef>();
    KsDef ksDef = new KsDef(keyspace,
            "org.apache.cassandra.locator.SimpleStrategy", cfDefList);
    ksDef.putToStrategy_options("replication_factor", "1");
    getConnection(null).system_add_keyspace(ksDef);
  }

  public void createColumnFamily(String keyspace, String columnFamilyName)
          throws Exception {
    CfDef columnFamily = new CfDef(keyspace, columnFamilyName);
    columnFamily.setKey_validation_class("UTF8Type");
    columnFamily.setComparator_type("UTF8Type");
    columnFamily.setDefault_validation_class("UTF8Type");
    getConnection(keyspace).system_add_column_family(columnFamily);
  }

}
